package images

import (
	"net/http"
	"server/internal/utils"

	"server/internal/common/biz"
	"server/internal/logic/images"
	"server/internal/svc"
	"server/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"
)

// pull image
func PullHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")
		var req types.PullImageReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		// 使用 FlushWriter 来支持 flush 操作
		flusher, ok := w.(http.Flusher)
		if !ok {
			http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
			return
		}

		respChan := make(chan string)
		errorChan := make(chan *biz.Error)
		l := images.NewPullLogic(r.Context(), svcCtx)
		go l.Pull(&req, respChan, errorChan)
		for {
			select {
			case bizErr := <-errorChan:
				_ = utils.SseFail(w, bizErr)
			case resp := <-respChan:
				_ = utils.SeeSuccess(w, resp)
			case <-r.Context().Done():
			}
			flusher.Flush()
		}

	}
}
